<template>
  <div v-if="!hasUserInfo">
    <div v-if="showBtn" class="div-pop" catchtouchmove="true">
      <div class="get-user-info">
        <div class="align-c pad-l-30 pad-r-30 mar-l-15 mar-r-15">
          <div class="text-align-c phone-info" :class="!pageType ? 'other-page' : ''">
            <div class="flex-center v-align-c height-96">
              <img v-if="appInfo.appLogo" class="width-96 height-96 avatar-bar" :src="appInfo.appLogo"/>
            </div>
            <div class="font-18 font-w mar-t-13">授权登录</div>
            <div class="font-15 font-color-9 mar-t-30 pad-t-16 mar-b-21">
              <div>为保障陛下您的体验旅程</div>
              <div>请先登录一下~</div>
            </div>
          </div>
          <div class='mar-t-20 width-per-100'>
            <button v-if="canIUseGetUserProfile" size="default" class="primary-button font-17 font-w" @tap="bindGetUserProfile">
              朕允了
            </button>
            <button v-else size="default" class="primary-button font-17 font-w" open-type="getUserInfo" lang="zh_CN" @getuserinfo="bindGetUserInfo">
              朕允了
            </button>
            <div class="font-12 font-color-9 text-align-c agree-bar">
              登录表示您已同意
              <span class="pad-t-9 pad-b-9" @click="agreeUser">《用户协议》</span>
              和<span class="pad-t-9 pad-b-9" @click="agreePrivacy">《隐私协议》</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { getMemberInfo, updateMember } from '@/api/home'
  import { decrypt } from '@/api/wechat'
  import { checkLogin } from '@/api/login'
  import { setVeekrayStatus, setCustomerId, setMemberId, setAnchorType, setNickName, setRoleType } from '@/utils/auth'

  export default {
    data() {
      return {
        isComponents: true,
        userInfo: {},
        hasUserInfo: false,
        showBtn: false,
        appInfo: {},
        scanCode: {},
        canIUseGetUserProfile: false
      }
    },
    props: {
      pageType: {
        type: String,
        default: ''
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
      setTimeout(() => {
        if (this.$pt.getStorageSync('appInfo')) {
          this.appInfo = this.$pt.getStorageSync('appInfo')
        }
      }, 500)
      if (this.$pt.getUserProfile) {
        this.canIUseGetUserProfile = true
      }
    },
    onShow() {
      this.getMemberInfo()
    },
    mounted() {
      setTimeout(() => {
        this.getMemberInfo()
      }, 100)
    },
    methods: {
      agreeUser() {
        this.$pt.navigateTo({url: '/pages/home/agree-user/main'})
      },
      agreePrivacy() {
        this.$pt.navigateTo({url: '/pages/home/agree-privacy/main'})
      },
      getMemberInfo() {
        if (this.$pt.getStorageSync('appInfo')) {
          this.appInfo = this.$pt.getStorageSync('appInfo')
        }
        if (!this.getCustomerId) {
          this.showBtn = true
          return false
        }
        // 访客基本信息, 用户已经授权过、登录过，已获取customerId，判断用户信息是否需要重新获取（重新授权）
        getMemberInfo(this.getCustomerId).then((response) => {
          if (response.isError) return
          if (!this.getCustomerId) {
            this.memberInfo.avatar = 'https://veekrayimg.joinsun.vip/head-portrait.png'
          }
          // 如果会员数据还没有更新，就获取会员信息。nickname、avatar、unionId三个信息不存在时，发起重新授权
          if (!response.data.nickname || !response.data.avatar) {
            setTimeout(() => {
              console.log('重新授权事件999')
              if (this.canIUseGetUserProfile) {
                this.getGetUserInfo('profile')
                return
              }
              this.getGetUserInfo('info')
            }, 100)
          } else {
            console.log('不重新授权事件888')
            this.hasUserInfo = true
            // 如果顾客已经是付费名片，要及时刷新缓存
            if (response.data.veekrayStatus === 1) {
              setVeekrayStatus(response.data.veekrayStatus)
            }
            if (!this.getMemberId) {
              setMemberId(this.appInfo.defaultMemberId)
              this.$utils.setMyId(this.appInfo.defaultMemberId)
            }
            if (this.$pt.getStorageSync('homeNone')) {
              this.$emit('updateUserInfo')
              this.$pt.removeStorageSync('homeNone')
            }
          }
        }).catch(() => {
        })
      },
      bindGetUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        this.$pt.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            console.log('bindGetUserProfile', res)
            this.common(res, 'profile')
          }
        })
      },
      bindGetUserInfo(e) {
        const res = e.mp.detail
        if (res) {
          this.common(res, 'info')
        }
      },
      common(resData, type) {
        this.userInfo = resData.userInfo
        // 记录到全局变量中
        this.globalData.userInfo = resData.userInfo
        this.hasUserInfo = true
        if (this.getCustomerId) {
          this.doUpdateMember(this.getCustomerId)
        } else {
          let myId = this.$pt.getStorageSync('myId')
          if (!myId && this.appInfo.defaultMemberId) {
            setMemberId(this.appInfo.defaultMemberId)
            this.$utils.setMyId(this.appInfo.defaultMemberId)
            // if (!this.$pt.getStorageSync('detailIncome')) {
            //   this.$pt.reLaunch({ url: '/pages/home/main?showPhonePage=1' })
            // }
          }
          let getUserInfo = this.$pt.getStorageSync('getUserInfo')
          if (getUserInfo) {
            switch (getUserInfo.path) {
              case 'pages/home/main':
                this.$pt.reLaunch({ url: '/pages/home/main?showPhonePage=1' })
                break
              case 'pages/shop/detail/main':
                setTimeout(() => {
                  if (getUserInfo.shareMemberId) {
                    this.$pt.reLaunch({
                      url: '/pages/shop/detail/main?memberId=' + getUserInfo.memberId + '&goodsId=' +
                        getUserInfo.goodsId + '&goodsType=' + getUserInfo.goodsType + '&shareMemberId' + getUserInfo.shareMemberId
                    })
                  } else {
                    this.$pt.reLaunch({
                      url: '/pages/shop/detail/main?memberId=' + getUserInfo.memberId + '&goodsId=' +
                        getUserInfo.goodsId + '&goodsType=' + getUserInfo.goodsType + '&shareMemberId='
                    })
                  }
                }, 800)
                break
            }
          } else {
            if (!this.$pt.getStorageSync('myId') && this.appInfo.defaultMemberId) {
              setMemberId(this.appInfo.defaultMemberId)
              this.$utils.setMyId(this.appInfo.defaultMemberId)
              // if (!this.$pt.getStorageSync('detailIncome')) {
              //   this.$pt.reLaunch({ url: '/pages/home/main?showPhonePage=1' })
              // }
            }
            if (this.$pt.getStorageSync('myId') && this.appInfo.defaultMemberId) {
              setMemberId(this.$pt.getStorageSync('myId'))
              this.$utils.setMyId(this.$pt.getStorageSync('myId'))
              this.getGetUserInfo(resData, type)
            }
          }
        }
      },
      getGetUserInfo(resData, type) {
        if (type === 'profile') {
          console.log('profile type1')
          this.hasUserInfo = true
          this.updateUnionId(resData)
        } else {
          console.log('userInfo type1')
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          this.$pt.getUserInfo({
            success: (res) => {
              this.userInfo = res.userInfo
              this.globalData.userInfo = res.userInfo
              this.hasUserInfo = true
              this.updateUnionId(res)
            }
          })
        }
      },
      doUpdateMember(customerId) {
        if (!customerId) return
        let data = {
          memberId: customerId,
          nickname: this.userInfo.nickName,
          avatar: this.userInfo.avatarUrl
        }
        if (!this.userInfo.nickName) {
          checkLogin(this.getMemberId)
          return
        }
        updateMember(data).then((response) => {
          if (response.isError) return
          this.$emit('updateUserInfo')
          console.log('保存访客信息')
        }).catch(() => {
        })
      },
      updateUnionId(res) {
        console.log('updateUnionId', res)
        // 保存unionId，同时插入/更新会员信息
        let data = {
          memberId: this.getCustomerId, // getCustomerId可为空值
          encryptedData: res.encryptedData,
          iv: res.iv,
          type: 2
        }
        if (!res.encryptedData) {
          this.$emit('showTabBar')
          this.$pt.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
          })
          return
        }
        decrypt(data).then((response) => {
          // 执行登录
          this.$utils.removeMyId('getUserInfo')
          if (response.data.customerId) {
            if (!this.$pt.getStorageSync('anchorAuth')) {
              setCustomerId(response.data.customerId)
            }
            this.getMemberInfoLast(response.data.customerId)
          }
          console.log('保存unionId')
        }).catch(() => {
        })
      },
      getMemberInfoLast(customerId) {
        getMemberInfo(customerId).then((response) => {
          if (response.isError) return
          if (this.getCurrentPage().page.route === 'pages/home/main') {
            this.$pt.hideTabBar({
              animation: false
            })
          }
          if (!this.$pt.getStorageSync('anchorAuth')) {
            setNickName(response.data.nickname)
          }
          if (response.data.veekrayStatus === 1) {
            setVeekrayStatus(response.data.veekrayStatus)
          }
          if (!this.getMemberId) {
            setMemberId(this.appInfo.defaultMemberId)
            this.$utils.setMyId(this.appInfo.defaultMemberId)
          }
          if (response.data.anchorAuthority !== undefined) {
            setAnchorType(response.data.anchorAuthority)
            if (this.pageType === 'getCard') {
              this.$pt.reLaunch({ url: '/pages/home/get-card/main' })
            } else {
              if (response.data.anchorAuthority !== 1) {
                this.$pt.navigateTo({ url: '/pages/personal/apply-anchor/main?inPage=1' })
              } else {
                setRoleType(1)
                this.$emit('updateUserInfo')
              }
            }
          }
        }).catch(() => {
        })
      }
    }
  }
</script>

<style scoped lang="less">
  .div-pop{
    z-index: 1201;
  }
  .get-user-info {
    width: 375px;
    height: calc(100vh);
    background-color: #fff;
    overflow: hidden;
    .phone-info{
      margin-top: 50px;
      &.other-page{
        margin-top: 75px;
      }
    }
    .avatar-bar{
      border-radius: 100px;
    }
    .primary-button{
      background: #ffe100;
      border-radius: 50px;
      margin-top: 30px;
      padding: 1px 0;
    }
    .agree-bar{
      span{
        display: inline-block;
        color: #5876B3;
      }
    }
    .top-nav{
      background: #ffffff;
      color: #333;
      box-sizing: border-box;
      text-align: center;
      font-size: 15px;
      position: fixed;
      width: 100%;
      left: 0;
      top: 0;
      z-index: 100;
      .top-txt{
        font-size: 18px;
        color: #333;
      }
    .self-back {
      width: 20rpx;
      height: 20rpx;
      border-top: 2px solid #000;
      border-left: 2px solid #000;
      transform: rotate(-45deg);
      position: absolute;
      left: 20rpx;
    }
    }
  }
</style>
